package cn.edu.zime.tjh.iotapp;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiService;
import cn.edu.zime.tjh.iotapp.model.Device;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import android.graphics.Color;
import android.content.Intent;
import android.net.Uri;

public class DeviceDetailActivity extends AppCompatActivity {
    
    private static final String TAG = "DeviceDetailActivity";
    
    // 设备信息
    private String deviceId;
    private String deviceName;
    private String deviceType;
    private Device deviceData;
    
    // UI组件
    private TextView textDeviceName;
    private TextView textDeviceType;
    private TextView textDeviceStatus;
    private TextView textLastActive;
    private TextView textLocation;
    private TextView textFirmware;
    private TextView textManufacturer;
    private TextView textModel;
    private TextView textNoData;
    
    private LineChart chartSensorData;
    private Spinner spinnerDataType;
    private Spinner spinnerTimeRange;
    private FloatingActionButton fabRefresh;
    
    // 数据类型和时间范围
    private String currentDataType;
    private int currentTimeRange = 24; // 默认24小时
    
    // API服务
    private ApiService apiService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);
        
        // 获取传递的设备信息
        deviceId = getIntent().getStringExtra("DEVICE_ID");
        deviceName = getIntent().getStringExtra("DEVICE_NAME");
        deviceType = getIntent().getStringExtra("DEVICE_TYPE");
        
        if (deviceId == null || deviceName == null) {
            Toast.makeText(this, "设备信息不完整", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 初始化API服务
        apiService = ApiService.getInstance();
        
        // 初始化UI
        initViews();
        
        // 设置下拉选择器
        setupSpinners();
        
        // 设置刷新按钮
        fabRefresh.setOnClickListener(v -> refreshDeviceData());
        
        // 初始加载设备数据
        loadDeviceDetail();
    }
    
    private void initViews() {
        textDeviceName = findViewById(R.id.textDeviceName);
        textDeviceType = findViewById(R.id.textDeviceType);
        textDeviceStatus = findViewById(R.id.textDeviceStatus);
        textLastActive = findViewById(R.id.textLastActive);
        textLocation = findViewById(R.id.textLocation);
        fabRefresh = findViewById(R.id.fabRefresh);
        
        // 添加缺失的视图初始化
        spinnerDataType = findViewById(R.id.spinnerDataType);
        spinnerTimeRange = findViewById(R.id.spinnerTimeRange);
        textNoData = findViewById(R.id.textNoData);
        chartSensorData = findViewById(R.id.chartSensorData);
        
        // 设置标题
        TextView titleText = findViewById(R.id.textTitle);
        if (titleText != null) {
            titleText.setText(deviceName);
        }
        
        // 设置基本设备信息
        textDeviceName.setText(deviceName);
        textDeviceType.setText(deviceType);
        
        // 初始化图表
        setupChart();
    }
    
    private void setupSpinners() {
        // 数据类型选择器
        List<String> dataTypes = new ArrayList<>();
        dataTypes.add("全部数据类型");
        dataTypes.add("温度");
        dataTypes.add("湿度");
        dataTypes.add("光照");
        dataTypes.add("压力");
        
        ArrayAdapter<String> dataTypeAdapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, dataTypes);
        dataTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerDataType.setAdapter(dataTypeAdapter);
        
        spinnerDataType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = parent.getItemAtPosition(position).toString();
                if (position == 0) {
                    currentDataType = null; // 全部数据类型
                } else if ("温度".equals(selected)) {
                    currentDataType = "temperature";
                } else if ("湿度".equals(selected)) {
                    currentDataType = "humidity";
                } else if ("光照".equals(selected)) {
                    currentDataType = "light";
                } else if ("压力".equals(selected)) {
                    currentDataType = "pressure";
                }
                
                // 加载选中类型的数据
                loadSensorData();
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        
        // 时间范围选择器
        List<String> timeRanges = new ArrayList<>();
        timeRanges.add("最近24小时");
        timeRanges.add("最近48小时");
        timeRanges.add("最近7天");
        timeRanges.add("最近30天");
        
        ArrayAdapter<String> timeRangeAdapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, timeRanges);
        timeRangeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTimeRange.setAdapter(timeRangeAdapter);
        
        spinnerTimeRange.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        currentTimeRange = 24;
                        break;
                    case 1:
                        currentTimeRange = 48;
                        break;
                    case 2:
                        currentTimeRange = 168; // 7天
                        break;
                    case 3:
                        currentTimeRange = 720; // 30天
                        break;
                }
                
                // 加载选中时间范围的数据
                loadSensorData();
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    
    private void setupChart() {
        // 配置图表
        chartSensorData.getDescription().setEnabled(false);
        chartSensorData.setTouchEnabled(true);
        chartSensorData.setDragEnabled(true);
        chartSensorData.setScaleEnabled(true);
        chartSensorData.setPinchZoom(true);
        chartSensorData.setDrawGridBackground(false);
        
        // X轴设置
        XAxis xAxis = chartSensorData.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        
        // 减少X轴标签数量，避免密集显示
        xAxis.setLabelCount(6, true); // 设置大约显示6个标签
        
        // 只显示时间，不显示日期
        xAxis.setValueFormatter(new ValueFormatter() {
            private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
            
            @Override
            public String getFormattedValue(float value) {
                return timeFormat.format(new Date((long) value));
            }
        });
        
        // 更多图表视觉优化
        xAxis.setDrawGridLines(false); // 不绘制网格线
        chartSensorData.getAxisLeft().setDrawGridLines(true); // 保留Y轴网格线
        chartSensorData.getAxisRight().setEnabled(false); // 禁用右侧Y轴
        
        // 添加额外的间距，使图表不会太拥挤
        chartSensorData.setExtraBottomOffset(10f);
        chartSensorData.setExtraLeftOffset(10f);
        chartSensorData.setExtraRightOffset(10f);
        
        // 初始状态下隐藏图表，显示无数据提示
        chartSensorData.setVisibility(View.GONE);
        textNoData.setVisibility(View.VISIBLE);
    }
    
    private void loadDeviceDetail() {
        apiService.getDeviceDetail(deviceId, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        JSONObject deviceData = response.getJSONObject("data");
                        
                        // 解析设备信息，同时处理两种可能的字段名格式
                        String deviceId = deviceData.has("device_id") ? deviceData.getString("device_id") : 
                                          (deviceData.has("id") ? deviceData.getString("id") : "");
                                          
                        String deviceName = deviceData.has("device_name") ? deviceData.getString("device_name") : 
                                            (deviceData.has("name") ? deviceData.getString("name") : "");
                                            
                        String deviceType = deviceData.has("device_type") ? deviceData.getString("device_type") : 
                                            (deviceData.has("type") ? deviceData.getString("type") : "");
                                            
                        String deviceStatus = deviceData.has("device_status") ? deviceData.getString("device_status") : 
                                              (deviceData.has("status") ? deviceData.getString("status") : "active");

                        // 处理设备网址信息，可能使用device_web或web_info
                        String deviceWeb = deviceData.has("device_web") ? deviceData.getString("device_web") : 
                                          (deviceData.has("web_info") ? deviceData.getString("web_info") : "");
                        
                        // 创建Device对象 - 使用无参构造器+setter方法
                        Device device = new Device();
                        device.setDevice_id(deviceId);
                        device.setDevice_name(deviceName);
                        device.setDevice_type(deviceType);
                        device.setDevice_status(deviceStatus);
                        
                        // 设置可选字段
                        if (deviceData.has("info") && !deviceData.isNull("info")) {
                            device.setDevice_info(deviceData.getString("info"));
                        }
                        
                        if (deviceWeb != null && !deviceWeb.isEmpty()) {
                            device.setDevice_web(deviceWeb);
                        }
                        
                        // 保存设备数据
                        DeviceDetailActivity.this.deviceData = device;
                        
                        // 更新UI
                        updateDeviceUI(device);
                        
                        // 加载传感器数据
                        loadSensorData();
                    } else {
                        String message = response.optString("message", "加载设备详情失败");
                        throw new Exception(message);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析设备详情失败: " + e.getMessage());
                    runOnUiThread(() -> {
                        Toast.makeText(DeviceDetailActivity.this, "加载设备详情失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
            
            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "加载设备详情失败: " + errorMsg);
                runOnUiThread(() -> {
                    Toast.makeText(DeviceDetailActivity.this, "加载设备详情失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    private void updateDeviceUI(Device device) {
        runOnUiThread(() -> {
            textDeviceName.setText(device.getDevice_name());
            textDeviceType.setText(device.getDevice_type());
            
            // 根据设备状态显示状态文本和颜色
            String status = device.getDevice_status();
            if ("active".equals(status)) {
                textDeviceStatus.setText("在线");
                textDeviceStatus.setTextColor(getResources().getColor(R.color.status_online));
            } else {
                textDeviceStatus.setText("离线");
                textDeviceStatus.setTextColor(getResources().getColor(R.color.status_offline));
            }
            
            // 设备信息应显示在设备信息字段，而不是最后活动时间字段
            LinearLayout layoutDeviceInfo = findViewById(R.id.layoutDeviceInfo);
            TextView textDeviceInfo = findViewById(R.id.textDeviceInfo);
            
            if (device.getDevice_info() != null && !device.getDevice_info().isEmpty()) {
                textDeviceInfo.setText(device.getDevice_info());
                layoutDeviceInfo.setVisibility(View.VISIBLE);
                
                // 最后活动时间字段暂时隐藏，或者使用其他字段数据
                findViewById(R.id.layoutLastActive).setVisibility(View.GONE);
            } else {
                layoutDeviceInfo.setVisibility(View.GONE);
                findViewById(R.id.layoutLastActive).setVisibility(View.GONE);
            }
            
            // 设备网址相关内容
            LinearLayout layoutDeviceWeb = findViewById(R.id.layoutDeviceWeb);
            if (layoutDeviceWeb != null) {
                TextView textDeviceWeb = findViewById(R.id.textDeviceWeb);
                ImageView imageQRCode = findViewById(R.id.imageQRCode);
                
                if (device.getDevice_web() != null && !device.getDevice_web().isEmpty()) {
                    String deviceWeb = device.getDevice_web();
                    textDeviceWeb.setText(deviceWeb);
                    
                    // 生成并显示二维码
                    Bitmap qrCodeBitmap = generateQRCode(deviceWeb, 500);
                    if (qrCodeBitmap != null) {
                        imageQRCode.setImageBitmap(qrCodeBitmap);
                        imageQRCode.setVisibility(View.VISIBLE);
                        
                        // 添加点击事件 - 点击二维码跳转到设备网址
                        imageQRCode.setOnClickListener(v -> {
                            try {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(deviceWeb));
                                startActivity(intent);
                            } catch (Exception e) {
                                Toast.makeText(DeviceDetailActivity.this, 
                                              "无法打开网址: " + e.getMessage(), 
                                              Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        imageQRCode.setVisibility(View.GONE);
                    }
                    
                    layoutDeviceWeb.setVisibility(View.VISIBLE);
                } else {
                    layoutDeviceWeb.setVisibility(View.GONE);
                }
            }
            
            // 如果没有详细信息，隐藏整个详情卡片
            boolean hasDetails = 
                (device.getDevice_info() != null && !device.getDevice_info().isEmpty()) ||
                (device.getDevice_web() != null && !device.getDevice_web().isEmpty());
            
            findViewById(R.id.cardDeviceDetails).setVisibility(hasDetails ? View.VISIBLE : View.GONE);
        });
    }
    
    private void loadSensorData() {
        apiService.getDeviceSensorHistory(deviceId, currentDataType, currentTimeRange, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    if (response.has("data") && !response.isNull("data")) {
                        JSONArray dataArray = response.getJSONArray("data");
                        
                        if (dataArray.length() == 0) {
                            runOnUiThread(() -> {
                                chartSensorData.setVisibility(View.GONE);
                                textNoData.setVisibility(View.VISIBLE);
                            });
                            return;
                        }
                        
                        // 分组不同类型的传感器数据
                        Map<String, List<Entry>> dataMap = new HashMap<>();
                        
                        for (int i = 0; i < dataArray.length(); i++) {
                            JSONObject item = dataArray.getJSONObject(i);
                            
                            String type = item.getString("type");
                            float value = (float) item.getDouble("value");
                            String timeStr = item.getString("time");
                            
                            // 解析时间 - 使用更灵活的方法处理不同格式
                            long timestamp = parseTimestamp(timeStr);
                            
                            // 添加数据点
                            if (!dataMap.containsKey(type)) {
                                dataMap.put(type, new ArrayList<>());
                            }
                            dataMap.get(type).add(new Entry(timestamp, value));
                        }
                        
                        // 创建数据集合
                        final List<LineDataSet> dataSets = new ArrayList<>();
                        
                        // 为每种类型创建一个数据集
                        for (Map.Entry<String, List<Entry>> entry : dataMap.entrySet()) {
                            String type = entry.getKey();
                            List<Entry> entries = entry.getValue();
                            
                            // 排序数据点（按时间戳）
                            entries.sort((e1, e2) -> Float.compare(e1.getX(), e2.getX()));
                            
                            LineDataSet dataSet = new LineDataSet(entries, getDisplayName(type));
                            dataSet.setDrawCircles(true);
                            dataSet.setCircleRadius(4f);
                            dataSet.setDrawValues(false);
                            dataSet.setLineWidth(2f);
                            
                            // 根据类型设置不同颜色
                            int color = getColorForType(type);
                            dataSet.setColor(color);
                            dataSet.setCircleColor(color);
                            
                            dataSets.add(dataSet);
                        }
                        
                        // 更新图表
                        runOnUiThread(() -> {
                            if (dataSets.isEmpty()) {
                                chartSensorData.setVisibility(View.GONE);
                                textNoData.setVisibility(View.VISIBLE);
                            } else {
                                LineData lineData = new LineData(dataSets.toArray(new LineDataSet[0]));
                                chartSensorData.setData(lineData);
                                chartSensorData.invalidate(); // 刷新图表
                                
                                chartSensorData.setVisibility(View.VISIBLE);
                                textNoData.setVisibility(View.GONE);
                            }
                        });
                    } else {
                        runOnUiThread(() -> {
                            chartSensorData.setVisibility(View.GONE);
                            textNoData.setVisibility(View.VISIBLE);
                        });
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "解析传感器数据失败: " + e.getMessage());
                    runOnUiThread(() -> {
                        Toast.makeText(DeviceDetailActivity.this, "加载传感器数据失败", Toast.LENGTH_SHORT).show();
                        chartSensorData.setVisibility(View.GONE);
                        textNoData.setVisibility(View.VISIBLE);
                    });
                }
            }
            
            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "获取传感器数据失败: " + errorMsg);
                runOnUiThread(() -> {
                    Toast.makeText(DeviceDetailActivity.this, "获取传感器数据失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                    chartSensorData.setVisibility(View.GONE);
                    textNoData.setVisibility(View.VISIBLE);
                });
            }
        });
    }
    
    /**
     * 将时间戳解析为UTC+8（中国时区）的时间
     */
    private long parseTimestamp(String timeStr) {
        // 尝试多种日期格式解析
        String[] dateFormats = {
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", // 带毫秒的ISO格式
            "yyyy-MM-dd'T'HH:mm:ss'Z'",     // 不带毫秒的ISO格式带Z
            "yyyy-MM-dd'T'HH:mm:ss",        // 不带毫秒和Z的ISO格式
            "yyyy-MM-dd HH:mm:ss"           // 普通日期时间格式
        };
        
        Date date = null;
        
        for (String format : dateFormats) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
                
                // 对于带Z结尾的ISO格式（表示UTC时间），设置时区为UTC
                if (format.endsWith("'Z'") && timeStr.endsWith("Z")) {
                    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                }
                
                date = sdf.parse(timeStr);
                if (date != null) {
                    break; // 成功解析，跳出循环
                }
            } catch (ParseException e) {
                // 继续尝试下一个格式
            }
        }
        
        // 如果所有格式都解析失败，返回当前时间
        if (date == null) {
            Log.w(TAG, "无法解析日期: " + timeStr + "，使用当前时间");
            return System.currentTimeMillis();
        }
        
        long timestamp = date.getTime();
        
        // 如果原始字符串以Z结尾（UTC时间），添加8小时转为UTC+8
        if (timeStr.endsWith("Z")) {
            timestamp += 8 * 60 * 60 * 1000; // 添加8小时
        }
        
        return timestamp;
    }
    
    private String getDisplayName(String type) {
        switch (type) {
            case "temperature":
                return "温度 (°C)";
            case "humidity":
                return "湿度 (%)";
            case "light":
                return "光照 (lx)";
            case "pressure":
                return "压力 (hPa)";
            default:
                return type;
        }
    }
    
    private int getColorForType(String type) {
        switch (type) {
            case "temperature":
                return getResources().getColor(android.R.color.holo_red_light);
            case "humidity":
                return getResources().getColor(android.R.color.holo_blue_light);
            case "light":
                return getResources().getColor(android.R.color.holo_orange_light);
            case "pressure":
                return getResources().getColor(android.R.color.holo_green_light);
            default:
                return getResources().getColor(android.R.color.darker_gray);
        }
    }
    
    private void refreshDeviceData() {
        // 刷新设备详情
        loadDeviceDetail();
        
        // 显示提示
        Toast.makeText(this, "正在刷新数据...", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 生成二维码
     * @param content 二维码内容
     * @param size 二维码大小（像素）
     * @return 生成的二维码图像
     */
    private Bitmap generateQRCode(String content, int size) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size);
            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
            
            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
                }
            }
            
            return bitmap;
        } catch (WriterException e) {
            Log.e(TAG, "生成二维码失败: " + e.getMessage());
            return null;
        }
    }

    public void back(View view) {
        finish();
    }
} 